<?php

namespace app\job\queue;

use think\facade\Log;
use think\queue\Job;
use app\common\enum\SystemNotifyStatusEnum;
use app\logic\im\MsgLogic;
use app\admin\model\system\Notify;

class ImSendMessageJob
{
    public function fire(Job $job, $data)
    {
        // 记录任务开始日志
        Log::channel('job')->info('ImSendMessageJob started with data: ' . json_encode($data));

        if ($job->attempts() > 3) {
            // 任务重试次数超过3次，标记为失败并删除任务
            Log::channel('job')->warning('ImSendMessageJob failed after 3 attempts');
            $job->failed($data);
            $job->delete();
            return;
        }

        try {
            $result = (new MsgLogic)->sendSystemMsg($data['user_id'], $data);
            if(isset($result['ErrorCode']) && $result['ErrorCode'] == 0){
                // 记录任务成功日志
                Log::channel('job')->info('ImSendMessageJob completed successfully: ' . json_encode($result));

                // 更新系统通知状态
                Notify::where('queue_id', $data['queue_id'])->update([
                    'push_status' => SystemNotifyStatusEnum::SUCCESS->value,
                    'push_time' => isset($result['MsgTime']) ? $result['MsgTime'] : null
                ]);
            }else{
                // 记录任务失败日志
                Log::channel('job')->warning('ImSendMessageJob failed: ' . json_encode($result));
            }

            // 删除rabbitmq队列
            $job->delete();

        } catch (\Throwable $e) {
            // 记录错误日志
            Log::channel('job')->error('Error processing ImSendMessageJob: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            throw $e;
        }
    }

    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
        custom_log(json_encode($data, 256), null, 'failed_job');
    }
}